
package cn.backflow.admin.controller;

import cn.backflow.admin.common.pagination.PageRequest;
import cn.backflow.lib.util.JsonMap;
import com.qiniu.http.Response;
import cn.backflow.admin.controller.base.BaseSpringController;
import cn.backflow.admin.entity.FileMapping;
import cn.backflow.admin.service.FileMappingService;
import cn.backflow.lib.thirdpart.QiniuUtil;
import cn.backflow.admin.common.secure.Permissions;;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("filemapping")
public class FileMappingController extends BaseSpringController {
    protected static final String DEFAULT_SORT_COLUMNS = "id desc"; // 默认排序, 如: id desc, created asc

    private QiniuUtil qiniuUtil = QiniuUtil.getInstance(QiniuUtil.Namespace.ADMIN);

    @Autowired
    private FileMappingService fileMappingService;

    /* 列表 */
    @Permissions("filemapping.view")
    public Object index(FileMapping fileMapping, HttpServletRequest request) throws Exception {
        PageRequest pr = pageRequest(request, DEFAULT_SORT_COLUMNS);
        pr.setPageSize(18);
        String mimetype = request.getParameter("mimetype");
        if ("*".equals(mimetype)) {
            pr.getFilters().remove("mimetype");
        }
        return fileMappingService.findPage(pr);
    }

    /* 显示 */
    @Permissions("filemapping.view")
    public Object byId(@PathVariable Integer id, HttpServletRequest request) throws Exception {
        JsonMap json = JsonMap.succeed();
        FileMapping fileMapping = fileMappingService.getById(id);
        json.put("fileMapping", fileMapping);
        return "filemapping/form";
    }


    /* 编辑 */
    @Permissions("filemapping.view")
    public String edit(@PathVariable Integer id, HttpServletRequest request) throws Exception {
        JsonMap json = JsonMap.succeed();
        FileMapping fileMapping = fileMappingService.getById(id);
        json.put("fileMapping", fileMapping);
        return "filemapping/form";
    }


    /* 保存新增 */
    @Permissions("filemapping.edit")
    public Object create(@Valid FileMapping fileMapping, BindingResult errors, HttpServletRequest request)
            throws Exception {
        JsonMap json = JsonMap.succeed();
        if (errors.hasErrors()) {
            return filedErrors(errors, json);
        }
        fileMappingService.save(fileMapping);
        return json;
    }

    @RequestMapping("upload")
    @Permissions("filemapping.upload")
    public Object upload(MultipartHttpServletRequest request) {
        JsonMap json = JsonMap.succeed();

        List<MultipartFile> filelist = request.getFiles("files");
        List<FileMapping> mappings = new ArrayList<>();
        List<String> failed = new ArrayList<>();
        Date now = new Date();
        try {
            for (MultipartFile file : filelist) {
                String folder = "admin/" + file.getContentType().split("/")[0] + "/";
                String key = qiniuUtil.buildKey(folder, file.getOriginalFilename());
                Response res = qiniuUtil.upload(file.getBytes(), key);
                if (!res.isOK()) {
                    failed.add(file.getOriginalFilename());
                    continue;
                }
                mappings.add(FileMapping.fromFileAndQiniuResponse(file, res, folder, now));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return json.success(false).msg(e.getMessage());
        }
        fileMappingService.save(mappings);
        if (!failed.isEmpty()) {
            json.put("failed", failed);
        }
        json.put("succeed", mappings);
        return json;
    }

    /* 保存更新 */
    @Permissions("filemapping.edit")
    public Object update(@PathVariable Integer id, @Valid FileMapping fileMapping, BindingResult errors, HttpServletRequest request) throws Exception {
        JsonMap json = JsonMap.succeed();
        if (errors.hasErrors()) {
            return filedErrors(errors, json);
        }
        fileMappingService.update(fileMapping);
        return json;
    }

    /* 批量删除 */
    @Permissions("filemapping.del")
    public Object delete(@RequestParam("items[]") Set<Integer> items, HttpServletRequest request) {
        fileMappingService.deleteBatch(items);
        return JsonMap.succeed();
    }

    /* 批量删除 */
    @RequestMapping("delete_by_keys")
    @Permissions("filemapping.del")
    public Object delete(@RequestParam("items[]") String[] items) throws Exception {
        fileMappingService.deleteByKeys(items);
        qiniuUtil.delete(items);
        return JsonMap.succeed();
    }
}